<template>
	<view class="test-detail">
		<scroll-view scroll-y class="scroll-review" :class="cboxcls">
			<view class="card">
				<view class="sentence-en">
					<view class="word-item" style="width: 30px"></view>
					<template v-for="item in sentenceItems" :key="item.Key">
						<view @tap="handleCleanInput(item)" v-if="item.isSpace" class="word-item real">
							<text class="word-input" :class="item.class">{{item.text}}</text>
							<text class="sort" :class="item.class">{{item.sort}}</text>
						</view>
						<view v-else class="word-item">
							<text class="word-input-text">{{item.text}}</text>
							<text class="sort"></text>
						</view>
					</template>
					<view v-if="!commitEnable" class="word-item">
						<view class="word-reset" @tap="handleClear()">重置</view>
						<text class="sort"></text>
					</view>
				</view>
			</view>
			<view class="card sentence-ch">
				<view style="text-indent: 2em;">{{ sentence ? sentence.SentenceCn : ''}}</view>
			</view>
			<view class="driver" v-if="!commitEnable"></view>
			<view class="card" v-if="!commitEnable">
				<view class="word-options">
					<view class="word-option" v-for="item in wordItems" :style="item.show?'':'visibility: hidden'"
						:key="item.WordId" @tap="handleToInput(item)">{{ item._SentenceWord }}</view>
				</view>
			</view>
			<view class="text-18 jump" style="display: flex;text-align: center; ">
				<view class="text-16" style="flex:1; color: #777;padding:10px;">
					<text v-if="jump && !commitEnable" @click="handleJump" style="">跳过</text>
					<text v-if="showTimer && !commitEnable && state.countdown>0"
						style="padding-left:10px;">({{state.countdown}}s)</text>
				</view>
			</view>
			<view class="driver"></view>
			<view class="flex-1">
				<view class="sentence-img"><u-image :src="sentence.Media" height="250px" mode="aspectFit"></u-image>
				</view>
			</view>
		</scroll-view>
		<view class="bottom-btn-box" v-if="firstFillCompleted || commitEnable">
			<u-button v-if="firstFillCompleted" @click="handleCommit" class="w-full" type="warning">提交</u-button>
			<u-button v-if="commitEnable" @click="handleNext" class="w-full" type="warning">继续</u-button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, nextTick, watch, inject, computed } from 'vue';
	import { ISentence, IWord, IWordIndexExt, useStudyStore } from '@/store/study';
	import { useSoundEffect, useTest, useTimer } from '@/common/hooks';
	import { getUuid, randomArray, deepClone } from '@/utils';

	/** 句词填充 */
	defineOptions({
		name: 'fill-sentence',
		inheritAttrs: false,
		options: {
			virtualHost: true
		}
	});

	/** 类型定义：组件参数 */
	type FillSentenceProps = {
		wordList : IWord[];
		sentence : ISentence;
		timerBarSty ?: string;
		jump ?: boolean;
		showTimer ?: boolean;
	}

	/** 组件参数 */
	const props = withDefaults(defineProps<FillSentenceProps>(), {
		wordList: () => [],
		timerBarSty: '',
		jump: false,
		showTimer: false
	});
	const emit = defineEmits(['next'])
	const isteacher = inject('isteacher')
	const isreview = inject('isreview')

	const studyStore = useStudyStore();
	const { state, startDownTime, clearTimer } = useTimer();
	const sentenceItems = ref<any[]>([]);
	const wordItems = ref<any[]>([]);
	const commitEnable = ref(false);
	// 首次填充完毕状态
	const firstFillCompleted = ref(false);
	const modelValue = ref<boolean>(false);
	const punctuationMark = ['.', ',', '?', '!'];

	const cboxcls = computed(() => {
		if (!isteacher && !isreview) {
			if (firstFillCompleted.value || commitEnable.value) {
				return 'teacher-rember-has-btn'
			} else {
				return 'teacher-rember'
			}
		}
		if (isteacher && isreview) {
			if (firstFillCompleted.value || commitEnable.value) {
				return 'teacher-review-has-btn'
			} else {
				return 'teacher-review'
			}
		}
		return '';
	})

	// 数据重置
	function reset() {
		sentenceItems.value = [];
		wordItems.value = [];
		modelValue.value = false;
		commitEnable.value = false;
		firstFillCompleted.value = false;
	}

	// 跳过事件
	function handleJump() {
		uni.showModal({
			content: '是否确认跳过?'
		}).then(res => {
			if (res.confirm) {
				clearTimer(true);
				handleNext();
			}
		})
	}

	// 判断是否是短语
	function isPhraseWord(inWord : IWordIndexExt) {
		if (inWord.Index.length <= 1) return false;
		if (inWord.Index.length > 1) {
			// 判断是否是连续索引
			const isLanxu = inWord.Index.reduce((prev, curr, index, arr) => {
				if (!prev) return false;
				if (index === 0) return true;
				return curr - arr[index - 1] === 1;
			}, true);

			return isLanxu;
		}
		return false;
	}
	
	/** 生成单词占位索引数据 */
	function generateWordSpaceIndex(sentence : ISentence) {
		// 占位索引记录
		const spaceArr = [];
		const descWordList = props.wordList.sort((a, b) => b.Word.split(' ').length - a.Word.split(' ').length)
		// 遍历词汇，生产渲染结构数据
		descWordList.forEach(wl => {
			// 词汇在句子中对应索引配套信息
			const IndexInfo = sentence.WordIds.find(wi => wi.Word === wl.Word);
			// 未匹配上，跳过
			if (!IndexInfo) return;
			
			// 占位索引的基础数据
			const tempSpace : any = {
				Key: getUuid(),
				WordId: wl.WordId,
				Word: wl.Word
			}
			
			// 是否是单词
			if (!/[^a-zA-Z]/.test(IndexInfo.Word)) {
				// [1,3,5] 有可能1是词组, 3或者5才是单词, 那么只能用3或者5
				const realIndex = IndexInfo.Index.find(idx => {
					const condition = (item : any) => item.Index.includes(idx) && /[^a-zA-Z]/.test(item.Word);
					const isPhrase = sentence.WordIds.some(wi => condition(wi))
					return !isPhrase
				})
				tempSpace.Index = [realIndex];
				tempSpace.Type = 'word';
				spaceArr.push(tempSpace);
				return;
			}
			
			// 是否是短语，这里跨索引的短语被舍弃了
			if (isPhraseWord(IndexInfo)) {
				tempSpace.Index = IndexInfo.Index;
				tempSpace.Type = 'phrase';
				spaceArr.push(tempSpace);
			}
		})
		return spaceArr;
	}
	/** 句子转对象 */
	function sentenceItemsParse(sentence : ISentence) {
		// 占位索引记录
		const spaceArr = generateWordSpaceIndex(sentence);
		console.log('spaceArr', spaceArr)
		const sentenceEnSp = sentence.SentenceEn.split(' ');
		let sort = 0;
		const tempSentenceItems = sentenceEnSp.flatMap<any>((sp, index, arr) => {
			const realIndex = index + 1;
			const saFoundIndex = spaceArr.findIndex(sa => sa.Index.includes(realIndex));
			if (saFoundIndex >= 0) {
				if (spaceArr[saFoundIndex].Index[0] === realIndex) {
					sort++;
					const word: string = spaceArr[saFoundIndex].Index.map((sai: number) => arr[sai-1]).join(' ');
					const mark = punctuationMark.find(tempMark => word.endsWith(tempMark))
					if (mark) {
						return [
							{
								...spaceArr[saFoundIndex],
								isSpace: true, 
								sort: sort,
								_SentenceWord: word.substring(0, word.length - 1)
							},
							{ text: mark },
							{ text: ' ' }
						]
						
					}
					return [
						{
							...spaceArr[saFoundIndex],
							isSpace: true, 
							sort: sort,
							_SentenceWord: word
						},
						{ text: ' ' }
					]
				}
				return []
			}
			return [
				{ text: sp },
				{ text: ' ' }
			]
		});
		console.log('tempSentenceItems', tempSentenceItems)
		return tempSentenceItems;
	}
	/** 初始化数据 */
	function initData(sentence : ISentence) {
		// 重置数据
		reset()
		if (!sentence) return;

		// 占位索引记录
		const tempSentenceItems = sentenceItemsParse(sentence);
		sentenceItems.value = tempSentenceItems;
		wordItems.value = randomArray(deepClone(props.wordList)).flatMap((item : IWord) => {
			const founds = tempSentenceItems.filter(si => si.WordId === item.WordId)
			return founds.map(ite => {
				return {
					...item,
					_SentenceWord: ite._SentenceWord,
					show: true
				}
			})
		})

		if (props.showTimer) {
			startDownTime(wordItems.value.length * 15, handleCommit);
		}
	}

	/** 清理填入内容 */
	function handleCleanInput(item : any) {
		if (props.showTimer) {
			// 倒计时归零了，停止答题操作
			if (state.value.countdown === 0) return;
		}
		// 已经提交答题，停止答题操作
		if (commitEnable.value) return;

		item.text = '';
		if (item.wordItem) {
			item.wordItem.show = true;
			item.wordItem = null;
		}
	}
	// 正确验证
	function validModelValue(needSetFirstFillDone : boolean = true) {
		const spaceList = sentenceItems.value.filter(si => si.isSpace);
		modelValue.value = spaceList.every(sl => {
			if (!sl.wordItem) return false;
			return sl.WordId === sl.wordItem.WordId
		})

		if (needSetFirstFillDone) {
			// 首次填充完毕状态更新
			const isDone = !sentenceItems.value.some(item => item.isSpace && item.text === '');
			if (isDone) {
				firstFillCompleted.value = true;
			}
		}
	}
	/** 单词填入 */
	function handleToInput(item : any) {
		// 倒计时归零了，停止答题操作
		if (props.showTimer) {
			// 倒计时归零了，停止答题操作
			if (state.value.countdown === 0) return;
		}
		// 已经提交答题，停止答题操作
		if (commitEnable.value) return;

		for (let i = 0; i < sentenceItems.value.length; i++) {
			if (!sentenceItems.value[i].text) {
				sentenceItems.value[i].text = item._SentenceWord;
				item.show = false;
				sentenceItems.value[i].wordItem = item;
				break;
			}
		}

		validModelValue();
	}

	/** 重置按钮事件 */
	function handleClear() {
		if (commitEnable.value) return;
		sentenceItems.value.forEach(item => {
			if (item.isSpace) {
				item.wordItem = null;
				item.text = '';
			}
		})
		wordItems.value.forEach(item => {
			item.show = true
		})
	}

	/** 提交按钮 */
	function handleCommit() {
		clearTimer();
		firstFillCompleted.value = false;
		commitEnable.value = true;
		// 1.将句子中的序号清空
		// 2.处理填充错误的样式，并将正确答案放在对应序号的位置
		sentenceItems.value.forEach(item => {
			if (item.isSpace) {
				item.sort = '';
				const isRight = item.wordItem ? item.WordId === item.wordItem.WordId && item.text === item._SentenceWord : false;
				if (isRight) {
					item.class = 'success';
				} else {
					item.sort = item._SentenceWord;
					item.class = 'error';
				}
			}
		})
	}
	/** 继续按钮 */
	function handleNext() {
		const isRight = modelValue.value;
		const answer = sentenceItems.value.filter(si => si.isSpace).map(si => {
			return {
				WordId: si.WordId,
				IsRight: si.class === 'success',
				AnswerWordId: si.wordItem ? si.wordItem.WordId : null,
				AnswerWord: si.wordItem ? si.wordItem.Word : null,
				AnswerMean: si.wordItem ? si.wordItem.Mean : null
			}
		})
		emit('next', props.sentence.SentenceEn, isRight, answer);
	}

	watch(
		() => props.sentence,
		nval => {
			initData(nval)
		},
		{ immediate: true }
	)
</script>

<style lang="scss" scoped>
	.test-detail {
		--card-out-width: 7px;
		--card-bg-color: rgba(252, 226, 191, 0.4);
		--card-line: 2px dashed rgba(195, 125, 56, 0.5);

		margin-top: 10px;
		border-radius: 5px;
		// background-color: var(--card-bg-color);

		.card {
			margin: 14px var(--card-out-width);
		}
	}

	.scroll-review {}

	/* #ifdef H5 */
	.scroll-review.teacher-rember {
		height: calc(100vh - 150px);
	}

	.scroll-review.teacher-rember-has-btn {
		height: calc(100vh - 200px);
	}

	.scroll-review.teacher-review {
		height: calc(100vh - 150px);
	}

	.scroll-review.teacher-review-has-btn {
		height: calc(100vh - 200px);
	}

	/* #endif */

	/* #ifdef MP */
	.scroll-review.teacher-rember {
		height: calc(100vh - 380rpx);
	}

	.scroll-review.teacher-rember-has-btn {
		height: calc(100vh - 460rpx);
	}

	.scroll-review.teacher-review {
		height: calc(100vh - 190rpx);
	}

	.scroll-review.teacher-review-has-btn {
		height: calc(100vh - 280rpx);
	}

	/* #endif */

	.sentence-img {
		margin-top: 10px;
		text-align: center;
	}

	.sentence-en {
		display: flex;
		flex-wrap: wrap;
	}

	.driver {
		border-top: 2px dashed rgba(0, 0, 0, 0.1);
		margin: 0px var(--card-out-width) 0;
	}

	.word-options {
		--item-width: 140rpx;
		--item-half-margin: 10rpx;

		display: flex;
		align-items: center;
		flex-wrap: wrap;
		box-sizing: border-box;

		.word-option {
			height: 80rpx;
			font-size: 40rpx;
			box-sizing: border-box;
			margin: 0 var(--item-half-margin) 24rpx var(--item-half-margin);
			background-color: #fce2bf;
			color: var(--font-color);
			border-radius: 16rpx;
			display: flex;
			padding-left: 8px;
			padding-right: 8px;
			justify-content: center;
			align-items: center;
		}
	}

	.sentence-ch {}

	.word-item {
		--font-size: var(--text-14);
		--height: 50rpx;

		display: flex;
		flex-flow: column;
		align-items: center;
		margin-bottom: 4px;

		.word-input {
			border: 1px solid transparent;
			border-bottom: 1px solid;
			min-width: 60px;
			font-size: var(--font-size);
			height: var(--height);
			text-align: center;

			&.success {
				color: #5ac725;
			}

			&.error {
				color: #ff0000;
			}
		}

		.sort.error {
			color: #5ac725;
		}

		.word-input-text {
			height: var(--height);
			font-size: var(--font-size);
			text-align: center;
			margin-right: 0.3ch;
			border: 1px solid transparent;
		}

		.word-reset {
			box-sizing: border-box;
			background-color: #fce2bf;
			color: var(--font-color);
			border-radius: 5px;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 6px 5px;
			margin-left: 5px;
			margin-right: 0.3ch;
			font-size: var(--font-size);
			height: var(--height);
		}
	}
</style>